<template lang="pug">
  div.mn
    div.hd
      top-banner
      split
    div.bd
      div.main-tt
        div.container
          div.tab-w
            div.tab-item(v-for="(item,index) in voteColumnList" :key="item.id" :class="{'active':item.id*1===currentVoteColumn.id*1}")
              div.tab-cell(type="primary" :disabled="!item.isActive" size="medium" @click="handlerClickBtnVoteColumn(item)") {{item.text}}
          <!--div.search-->
          <!--div.search-ipt-->
          <!--el-input(placeholder="请输入内容" suffix-icon="el-icon-search" v-model="searchStr" size="small")-->
          <!--el-button(type="primary" size="small" @click="handlerClickBtnSearch") 搜索-->
          <!--el-button(v-if="searchStr" type="danger" size="small" @click="handlerClickBtnClear") 清除-->
        split
      div.main
        div.container
          div.cells(v-if="voteItemList.length")
            div.cell-w(v-for="(item,index) in voteItemList" :key="item.id" )
              div.cell(@click="handlerClickVoteItem(item)")
                div.avatar-w
                  div.avatar-mn
                    div.avatar(:style="avatarStyle(item)")
                div.text(v-if="currentVoteColumn.id!==3")
                  div.txt-b--1 {{item.department}}
                div.text
                  div.txt-a(v-if="currentVoteColumn.id===1")
                    div.txt-a--1 {{item.courseName}}
                  div.txt-a(v-if="currentVoteColumn.id===2")
                    div.txt-a--1 {{item.name}}
                  div.txt-a(v-if="currentVoteColumn.id===3")
                    div.txt-a--1 {{item.name}}
                div.btn-w
                  div.btn {{item.voteCount||0}} 票
          div.loading-w(v-else)
            div.loading-msg
              i.el-icon-loading.icon
              span.txt 请稍后……
</template>

<script type="text/ecmascript-6">
import {voteCourseItemURL, voteTeacherItemURL, voteTeamItemURL, voteSaveURL} from '../config/global.toml'
import VoteTitle from '../components/VoteTitle'
import Split from '../components/Split'
import TopBanner from '../components/TopBanner'
import {mapGetters, mapActions} from 'vuex'

export default {
  metaInfo: {
    title: '得票统计'
  },
  data() {
    return {
      searchStr: null,
      voteColumnList: [],
      voteItemList: [],
      courseChecked: {},
      minItemLength: 2,
      maxItemLength: 4
    }
  },
  mounted() {
    console.log('asdf')
    this.getVoteColumn()
  },
  methods: {
    ...mapActions(['setCurrentVoteColumn']),
    getAvatar(item) {
      let name = this.currentVoteColumn.id === 1 ? item.courseName : item.name
      let researchSection = this.currentVoteColumn.id === 3 ? item.teamBelongs : item.researchSection
      return `/static/avatar/${researchSection}${name}.jpg`
    },
    avatarStyle(item) {
      return {'background-image': `url(${this.getAvatar(item)})`}
    },
    async getVoteColumn() {
      let targetUrls = [
        {
          text: '最受学员欢迎的课程',
          url: voteCourseItemURL,
          maxItemLength: 10,
          minItemLength: 5
        },
        {
          text: '最受学员喜爱的教员',
          url: voteTeacherItemURL,
          maxItemLength: 10,
          minItemLength: 5
        },
        {
          text: '最受学员信服的队干部',
          url: voteTeamItemURL,
          maxItemLength: 5,
          minItemLength: 1
        }
      ]
      let voteColumns = []
      for (let key in targetUrls) {
        let item = targetUrls[key]
        let {data: {data, totalCount}} = await this.$http.get(item.url, {
          params: {
            showType: '0'
          }
        })
        // let voteList = data[0].voteList
        let voteConfig = data[0].voteConfig
        // let isActive = voteList[0].voteCount === null
        // let text = voteConfig.voteName
        let voteColumn = {
          id: voteConfig.id,
          text: item.text,
          totalCount,
          url: item.url,
          maxItemLength: item.maxItemLength,
          minItemLength: item.minItemLength,
          isActive: true
        }
        voteColumns.push(voteColumn)
      }
      this.voteColumnList = voteColumns
      let cVC = voteColumns[0]
      let id = this.$route.params.id
      if (id) {
        cVC = voteColumns.find(e => {
          return e.id === id * 1
        })
      }
      this.handlerClickBtnVoteColumn(cVC)
    },
    handlerClickBtnVoteColumn(item) {
      this.$router.push({name: 'Statistic', params: {id: item.id}})
      this.setCurrentVoteColumn({
        id: item.id,
        mainTitle: item.text,
        endDate: item.endDate,
        startDate: item.startDate,
        voteType: item.voteType,
        maxItemLength: item.maxItemLength,
        minItemLength: item.minItemLength,
        url: item.url,
        voteList: item.voteList,
        totalCount: item.totalCount
      })
      this.getVoteItems()
    },
    async getVoteItems() {
      let targetUrl = this.currentVoteColumn.url
      console.log('targetUrl:', targetUrl)
      this.voteItemList = []
      let {data: {data, totalCount}} = await this.$http.get(targetUrl, {
        params: {
          showType: '1'
        }
      })
      console.log('totalCount:', totalCount)
      console.log('voteConfig:', data[0].voteConfig)
      console.log('data:', data[0].voteList)
      let voteConfig = data[0].voteConfig
      this.currentVoteColumn.endDate = voteConfig.endDate
      this.currentVoteColumn.startDate = voteConfig.startDate
      this.currentVoteColumn.voteType = voteConfig.voteType
      this.minItemLength = this.currentVoteColumn.minItemLength
      this.maxItemLength = this.currentVoteColumn.maxItemLength
      let tempVoteItem = data[0].voteList
      if (this.searchStr) {
        tempVoteItem = tempVoteItem.filter(e => {
          return e.name.indexOf(this.searchStr) > -1
        })
        console.log('1 tempVoteItem', tempVoteItem)
      }
      console.log('2 tempVoteItem', tempVoteItem)
      this.voteItemList = tempVoteItem
      this.voteItemList.map(e => {
        this.$set(e, 'isChecked', false)
      })
    },
    /**
     * 选项点击事件
     * @param item
     */
    handlerClickVoteItem(item) {
      if (this.currentVoteColumn.id !== 1) {
        this.$KalixVoteDetail({
          avatar: `/static/img/${item.researchSection}${item.name}.jpg`,
          title: item.name,
          html: item.description
        })
      }
    },
    /**
     * 选项选中事件
     * @param item
     */
    handlerClickVoteItemCheck(item) {
      console.log('item', item)
      if (!item.isChecked) {
        if (this.voteItemsIsChecked.length < this.maxItemLength) {
          item.isChecked = true
        } else {
          this.showMessage(`最多只能选择 ${this.maxItemLength} 个选项！`)
        }
      } else {
        item.isChecked = !item.isChecked
      }
    },
    /**
     * 搜索按钮点击事件
     * @param item
     */
    handlerClickBtnSearch() {
      this.getVoteItems()
    },
    handlerClickBtnClear() {
      this.searchStr = null
      this.getVoteItems()
    },
    showMessage(message, type = 'error') {
      this.$message({
        message,
        showClose: true,
        type,
        duration: 2000
      })
    },
    async handlerClickBtnSubmit() {
      if (this.voteItemsIsChecked.length < this.minItemLength) {
        this.showMessage(`至少选择 ${this.minItemLength} 个`)
      } else {
        let result = []
        this.voteItemsIsChecked.forEach(e => {
          result.push(e.id)
        })
        let voteUserId = this.userId
        let startDate = this.currentVoteColumn.startDate
        let endDate = this.currentVoteColumn.endDate
        let voteDate = new Date().getTime()
        let contents = result.join(`,`)
        let voteType = this.currentVoteColumn.voteType
        let voteSubmitData = {voteUserId, startDate, endDate, voteDate, contents, voteType}
        console.log('voteSubmitData:', voteSubmitData)
        let {data: {msg}} = await this.$http.post(voteSaveURL, voteSubmitData)
        this.$alert(msg, '', {
          confirmButtonText: '确定',
          callback: () => {
            this.$router.push({name: 'VoteColumn'})
          }
        })
      }
    }
  },
  computed: {
    ...mapGetters(['userId', 'currentVoteColumn']),
    btnDisabled() {
      return !(this.voteItemsIsChecked.length >= this.minItemLength && this.voteItemsIsChecked.length <= this.maxItemLength)
    },
    voteItemsIsChecked() {
      return this.voteItemList.filter(e => {
        return e.isChecked
      })
    }
  },
  components: {
    VoteTitle,
    Split,
    TopBanner
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "../assets/stylus/VoteHome.styl"
</style>
